<?php

namespace App\Dao;

use App\Model\BillsModel;
use App\Model\BillsScoreModel;

class BillsScoreDao extends BaseDao
{
    public static function bills_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = BillsScoreModel::query();
        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'title_like'),function ($query)use ($params){
            $query->where('title','like','%'.$params['title_like'].'%');
        });

        $query->when(checkIsHasField($params,'start_time'),function ($query)use ($params){
            $query->where('created_at','>=',strtotime($params['start_time']));
        });

        $query->when(checkIsHasField($params,'end_time'),function ($query)use ($params){
            $query->where('created_at','<=',strtotime($params['end_time'].' 23:59:59'));
        });


        return $query;
    }


    //更新用户余额
    public static function moneyUpdate($user_id = 0,$nums = 0,$title = '')
    {

        UsersDao::builder_user_query([
            'user_id'=>$user_id
        ])->increment('score',$nums);

        //添加记录
        self::bills_query()->create([
            'user_id'=>$user_id,
            'nums'=>$nums,
            'title'=>$title,
            'balance'=>UsersDao::builder_user_query([
                'user_id'=>$user_id
            ])->value('score')
        ]);
    }

    public static function pageinate(array $params)
    {
        return self::bills_query($params)->orderByDesc('created_at')->paginate();
    }

    public static function plutocrats()
    {
        //根据金币进行排行
        $all_scores = self::bills_query();
        $all_scores = $all_scores
            ->whereRaw(" (title LIKE '%动态%' OR title LIKE '%消费获取绿色消费金币%')")
            ->selectRaw("sum(nums) as sums_nums,user_id")
            ->groupBy('user_id')
            ->orderByDesc('sums_nums')
            ->with('userInfo')->get();
        $usersList = UsersDao::builder_user_query()->where('user_id','<>',CommonDao::$user_sys_id)->where('user_id','<>',10002)->where('score','<>',0)->orderByDesc('score')->get()->toArray();
        $dataList = [];
        foreach ($usersList as $value){
            $dataList[] = [
                'sums_nums'=>$value['score'],
                'user_info'=>$value,
                'user_id'=>$value['user_id']
            ];
        }
        return $dataList;
    }
}
